<template>
<el-menu
  :default-active="activePath"
  class="el-menu-vertical-demo"
  :router="true"
  background-color="lightgreen"
>
  <!-- 使用 v-for 遍历菜单项 -->
  <template v-for="route in authMenuList" :key="route.path">
    <!-- 没有子路由直接展示 -->
    <el-menu-item
      v-if="!route.children"
      :index="route.path"
      @click="handleClick(route.path)"
    >
      <template #title>
        <span>{{ route.meta.title }}</span>
      </template>
    </el-menu-item>
    
    <!-- 有一个子路由直接展示子路由 -->
    <el-menu-item
      v-if="route.children && route.children.length === 1"
      :index="route.children[0].path"
      @click="handleClick(route.children[0].path)"
    >
      <template #title>
        <span>{{ route.children[0].meta.title }}</span>
      </template>
    </el-menu-item>
    
    <!-- 有多个子路由进行组件递归处理 -->
    <el-sub-menu
      v-if="route.children && route.children.length > 1"
      :index="route.path"
    >
      <template #title>
        <span>{{ route.meta.title }}</span>
      </template>
      <RecursiveMenuComponent :authMenuList="route.children" />
    </el-sub-menu>
  </template>
</el-menu>
</template>

<script setup>
import { defineComponent, defineAsyncComponent, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'

// props
const props = defineProps({
  authMenuList: {
    type: Array,
    required: true
  }
})

// 保证菜单不会因为刷新也丢失选中状态 可能存在设计问题 黄色警告无法消除
const route = useRoute()
const activePath = computed(() => route.path)

// 路由跳转
const router = useRouter()
const handleClick = (path) => {
  router.push(path)
}

// 异步组件+组件显式命名 避免出现自身引用时 出现未注册的错误
const RecursiveMenuComponent = defineAsyncComponent(() => import('./RecursiveMenuComponent.vue'))
defineComponent({
  name: 'RecursiveMenuComponent',
})

</script>